using UnityEngine;
using System.Collections;

public class Notes : MonoBehaviour 
{
	AudioSource[] notes;
	int stairPosition;
	bool freshStair = true;
	int count = 0;
	float timeSinceLast = 0;
	float overall = 0;
	
	int currentBeat = 0;
	
	float beat0 = 0;
	float beat1 = 0.4615f;
	float beat2 = 0.923f;
	float beat3 = 1.3845f;
	
	bool shouldPlayBeat = false;
	int beatToPlay = 0;
	float beatTimer;

	// Use this for initialization
	void Start () 
	{
		notes = GetComponents<AudioSource>();	
		//Debug.Log("Length is: "+notes.Length);
	}
	
	// Update is called once per frame
	void Update () 
	{
		beatTimer = GameObject.FindGameObjectWithTag("AudioPlayer").GetComponent<AudioSource>().time;
		
		if(Input.GetButtonDown("Start"))
		{
			freshStair = true;
			currentBeat = 0;
			
		} 
		
		if(Input.GetButtonDown("Dash"))
		{
			count++;
			timeSinceLast = GameObject.FindGameObjectWithTag("AudioPlayer").GetComponent<AudioSource>().time - timeSinceLast;
			overall+=timeSinceLast;
			
			if(count>=20)
			{
				Debug.Log ("Beat time is");
			}
			//Debug.Log ("Distance from beat is "+ GameObject.FindGameObjectWithTag("AudioPlayer").GetComponent<AudioSource>().time);
		}

		determineCurrentBeat();
		
	}
	
	public void determineCurrentBeat()
	{
		if(currentBeat == 0)
		{
			if(beatTimer>=beat1)
			{
				currentBeat = 1;
				
				if(shouldPlayBeat)
				{
					//Debug.Log ("Beat played at 1");
					shouldPlayBeat = false;
					notes[beatToPlay].Play();
				}
			}
		}
		else if(currentBeat == 1)
		{
			if(beatTimer>=beat2)
			{
				currentBeat = 2;
				
				if(shouldPlayBeat)
				{
					//Debug.Log ("Beat played at 2");
					shouldPlayBeat = false;
					notes[beatToPlay].Play();
				}
			}
		}
		else if(currentBeat == 2)
		{
			if(beatTimer>=beat3)
			{
				currentBeat = 3;
				
				if(shouldPlayBeat)
				{
					//Debug.Log ("Beat played at 3");
					shouldPlayBeat = false;
					notes[beatToPlay].Play();
				}
			}
		}
		else if(currentBeat == 3)
		{
			if(beatTimer<=beat1 && beatTimer >=beat0)
			{			
				currentBeat = 0;
				
				if(shouldPlayBeat)
				{
					//Debug.Log ("Beat played at 0");
					shouldPlayBeat = false;
					notes[beatToPlay].Play();
				}
			}
		}
	}
	
	public void playNote()
	{
		//notes[Random.Range(0, notes.Length-1)].Play();
		//Debug.Log ("Distance from beat is "+ GameObject.FindGameObjectWithTag("AudioPlayer").GetComponent<AudioSource>().time);
		
		beatToPlay = Random.Range(0, notes.Length-3);
		shouldPlayBeat = true;
		//Debug.Log("Should play note");
	}
	
	public void playStairs(int size, bool finalStair)
	{
		if(freshStair)
		{
			//size of array problem
			freshStair = false;
			stairPosition = Random.Range(notes.Length, size) -1;
			//Debug.Log("Stair start is: "+stairPosition);
		}
		else
		{
			stairPosition--;
		}
		 
		//notes[stairPosition].Play();
		beatToPlay = stairPosition;
		shouldPlayBeat = true;
		
		
		if(finalStair)
		{
			freshStair = true;
		}
	}
}
